package com.magic.shop.handler;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.Nullable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 *
 * ma用户权限缓存
 */
@Slf4j
@Component
public class UserGroupCacheHandler {

//    @Autowired
//    private IMagicUserGroupService userGroupService;


    //测试用户权限---可以查看哪些包
    static Map<String,Set<String>> testGroupPermissonMap=new HashMap();
    static {
        Set<String> aa=new HashSet<>();
        aa.add("df6d81d2d0a849e0b46d8fac0d3df72e");//df6d81d2d0a849e0b46d8fac0d3df72e文件id
        testGroupPermissonMap.put("2",aa);
    }


    /**
     * 该缓存在项目启动的时候实例化，第一次userGroupCache.get的时候会调用下面的load方法
     */
    // 这里的权限缓存可以和登录token有效期一致
    LoadingCache<String, Set<String>> userGroupCache = Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.HOURS)
            .initialCapacity(10)
            .maximumSize(100)
            .recordStats()
            //当Entry被移除时的监听器
            .removalListener((key, value, removalCause) -> log.info("remove cache:{}-{}, cause:{}", key, value, removalCause))
            .build(new CacheLoader<String, Set<String>>() {
                //第一次userGroupCache.get的时候会调用
                @Override
                public @Nullable Set<String> load(String key) throws Exception {
                    //查数据库return userGroupService.lambdaQuery().eq(MagicUserGroup::getUserId, key).list().stream().map(MagicUserGroup::getGroupId).collect(Collectors.toSet());

                    Set<String> testSets = testGroupPermissonMap.get(key);

                    return testSets;
                }
            });

    public Set<String> getUserGroupIds(String userId) {
        return this.userGroupCache.get(userId);
    }

    public void removeKey(String userId) {
        this.userGroupCache.invalidate(userId);
    }

    public void refresh(String userId){
        this.userGroupCache.refresh(userId);
    }
}
